const { list } = require('../mock/mock');
const BluetoothLockDevice = require('../models/BluetoothLockDevice');
const ContainerDevice = require('../models/ContainerDevice');
const BluetoothLockOpenRecord = require('../models/BluetoothLockOpenRecord');
const { Op } = require('sequelize');

const smartLockController = {
  // 通用响应格式
  sendResponse: (res, data, total = 0, pageSize = 10, currentPage = 1) => {
    res.json({
      success: true,
      data: {
        list: data,
        total,
        pageSize,
        currentPage
      }
    });
  },

  // 蓝牙锁设备管理
  getDeviceList: async (req, res) => {
    try {
      const { pageSize = 10, currentPage = 1, lockId, position } = req.body;
      
      // 构建查询条件
      const where = {};
      if (lockId) where.lockId = lockId;
      if (position) where.position = position;

      // 计算偏移量
      const offset = (currentPage - 1) * pageSize;

      // 查询数据
      const { count, rows } = await BluetoothLockDevice.findAndCountAll({
        where,
        limit: pageSize,
        offset,
        order: [['id', 'DESC']]
      });

      // 格式化返回数据
      const formattedData = rows.map((item, index) => ({
        id: item.id,
        lockId: item.lockId,
        model: item.model,
        name: item.name,
        active: item.active,
        position: item.position,
        department: item.department,
        lockStatus: item.lockStatus,
        lng: item.lng,
        lat: item.lat,
        dis: item.dis,
        remark: item.remark,
        opDate: item.opDate,
        alias: item.alias,
        oName: item.oName,
        createdAt: item.createdAt,
        updatedAt: item.updatedAt
      }));

      res.json({
        success: true,
        data: {
          list: formattedData,
          total: count,
          pageSize,
          currentPage
        }
      });
    } catch (error) {
      console.error('获取设备列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取设备列表失败',
        error: error.message
      });
    }
  },

  getRecordList: async (req, res) => {
    try {
      const { 
        pageSize = 10, 
        currentPage = 1, 
        username, 
        deviceId, 
        operatingTime, 
        id, 
        name 
      } = req.body;
      
      // 构建查询条件
      const where = {};
      if (username) where.username = username;
      if (deviceId) where.deviceId = deviceId;
      if (operatingTime) where.operatingTime = operatingTime;
      if (id) where.id = id;
      if (name) where.name = name;

      // 计算偏移量
      const offset = (currentPage - 1) * pageSize;

      // 查询数据
      const { count, rows } = await BluetoothLockDevice.findAndCountAll({
        where,
        limit: pageSize,
        offset,
        order: [['id', 'DESC']],
        attributes: [
          'id',
          'lockId',
          'model',
          'name',
          'active',
          'position',
          'department',
          'lockStatus',
          'opDate'
        ]
      });

      // 格式化返回数据
      const formattedData = rows.map((item, index) => ({
        xuHao: index + 1 + offset, // 序号
        lockId: item.lockId, // 锁ID
        model: item.model, // 设备型号
        name: item.name, // 设备名称
        status: item.active ? '正常' : '异常', // 状态
        position: item.position, // 位置
        department: item.department, // 所属机构
        lockStatus: item.lockStatus, // 状态
        operatingTime: item.opDate // 操作时间
      }));

      res.json({
        success: true,
        data: {
          list: formattedData,
          total: count,
          pageSize,
          currentPage
        }
      });
    } catch (error) {
      console.error('获取蓝牙锁记录失败:', error);
      res.status(500).json({
        success: false,
        message: '获取蓝牙锁记录失败',
        error: error.message
      });
    }
  },

  getTypeList: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现型号管理逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  openLock: async (req, res) => {
    try {
      const { pageSize = 10, currentPage = 1, username, startDate, endDate } = req.body;
      
      // 构建查询条件
      const where = {};
      if (username) where.username = username;
      if (startDate) where.startDate = { [Op.gte]: startDate };
      if (endDate) where.endDate = { [Op.lte]: endDate };

      // 计算偏移量
      const offset = (currentPage - 1) * pageSize;

      // 查询数据
      const { count, rows } = await BluetoothLockOpenRecord.findAndCountAll({
        where,
        include: [{
          model: BluetoothLockDevice,
          through: { attributes: [] }
        }],
        limit: pageSize,
        offset,
        order: [['id', 'DESC']]
      });

      // 格式化返回数据
      const formattedData = rows.map((item, index) => ({
        id: item.id,
        username: item.username,
        startDate: item.startDate,
        endDate: item.endDate,
        remark: item.remark,
        startTime: item.startTime,
        endTime: item.endTime,
        deviceList: item.BluetoothLockDevices.map(device => ({
          id: device.id,
          lockId: device.lockId,
          model: device.model,
          name: device.name,
          active: device.active,
          position: device.position,
          department: device.department,
          lockStatus: device.lockStatus,
          lng: device.lng,
          lat: device.lat,
          dis: device.dis,
          remark: device.remark,
          opDate: device.opDate,
          alias: device.alias,
          oName: device.oName
        }))
      }));

      res.json({
        success: true,
        data: {
          list: formattedData,
          total: count,
          pageSize,
          currentPage
        }
      });
    } catch (error) {
      console.error('获取开锁授权记录失败:', error);
      res.status(500).json({
        success: false,
        message: '获取开锁授权记录失败',
        error: error.message
      });
    }
  },

  // 电子钥匙相关
  getKeyRecord: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现电子钥匙记录查询逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  openKey: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现电子钥匙开锁授权逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  getKeyDevice: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现电子钥匙设备管理逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  getKeyDeviceKey: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现电子钥匙设备密钥逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  getKeyDeviceCore: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现电子钥匙设备核心逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  // 网控器相关
  getControllerRecord: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现网控器记录查询逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  getControllerUpgrade: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现网控器型号管理逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  openController: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现网控器开锁授权逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  getControllerDevice: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现网控器设备管理逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  // 箱柜相关
  getContainerRecord: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现箱柜记录查询逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  getContainerSet: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现箱柜型号管理逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  openContainer: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现箱柜开锁授权逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  getContainerDevice: async (req, res) => {
    try {
      const { pageSize = 10, currentPage = 1, containerId, position } = req.body;
      
      // 构建查询条件
      const where = {};
      if (containerId) where.containerId = containerId;
      if (position) where.position = position;

      // 计算偏移量
      const offset = (currentPage - 1) * pageSize;

      // 查询数据
      const { count, rows } = await ContainerDevice.findAndCountAll({
        where,
        limit: pageSize,
        offset,
        order: [['id', 'DESC']]
      });

      res.json({
        success: true,
        data: {
          list: rows,
          total: count,
          pageSize,
          currentPage
        }
      });
    } catch (error) {
      console.error('获取箱柜设备列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取箱柜设备列表失败',
        error: error.message
      });
    }
  },

  // 新增箱柜设备
  createContainerDevice: async (req, res) => {
    try {
      const devices = Array.isArray(req.body) ? req.body : [req.body];
      const createdDevices = await ContainerDevice.bulkCreate(devices);
      res.json({
        success: true,
        message: '设备创建成功',
        data: createdDevices
      });
    } catch (error) {
      console.error('创建设备失败:', error);
      res.status(500).json({
        success: false,
        message: '创建设备失败',
        error: error.message
      });
    }
  },    

  getContainerStatus: (req, res) => {
    const { pageSize = 10, currentPage = 1 } = req.body;
    // TODO: 实现箱柜实时状态逻辑
    const mockData = [];
    smartLockController.sendResponse(res, mockData, 0, pageSize, currentPage);
  },

  // 新增蓝牙锁设备
  createDevice: async (req, res) => {
    try {
      const devices = Array.isArray(req.body) ? req.body : [req.body];
      const createdDevices = await BluetoothLockDevice.bulkCreate(devices);
      
      res.json({
        success: true,
        message: '设备创建成功',
        data: createdDevices
      });
    } catch (error) {
      console.error('创建设备失败:', error);
      res.status(500).json({
        success: false,
        message: '创建设备失败',
        error: error.message
      });
    }
  },

  // 新增开锁授权
  createOpenLock: async (req, res) => {
    try {
      const { username, deviceList, startTime, endTime, name, operatingTime } = req.body;
      
      // 创建授权记录
      const record = await BluetoothLockOpenRecord.create({
        username,
        startTime,
        endTime,
        name: name || null,
        operatingTime: operatingTime || null,
        lockId: '', // 默认值
        position: ' ', // 默认值
        active: true
      });

      // 关联设备
      if (deviceList) {
        // 处理逗号分隔的设备ID字符串
        const deviceIds = typeof deviceList === 'string' 
          ? deviceList.split(',').map(id => id.trim())
          : Array.isArray(deviceList) ? deviceList : [deviceList];

        const devices = await BluetoothLockDevice.findAll({
          where: { id: deviceIds }
        });
        
        if (devices.length > 0) {
          await record.setBluetoothLockDevices(devices);
        }
      }

      // 获取完整的记录（包括关联的设备）
      const fullRecord = await BluetoothLockOpenRecord.findByPk(record.id, {
        include: [{
          model: BluetoothLockDevice,
          through: { attributes: [] }
        }]
      });

      res.json({
        success: true,
        message: '开锁授权创建成功',
        data: fullRecord
      });
    } catch (error) {
      console.error('创建开锁授权失败:', error);
      res.status(500).json({
        success: false,
        message: '创建开锁授权失败',
        error: error.message
      });
    }
  }
};

module.exports = smartLockController; 